package com.example.verify.handler;

import com.example.annotations.Length;
import com.example.annotations.NotNull;
import com.example.annotations.Phone;
import com.example.annotations.handler.VerifyHandler;
import com.example.exceptions.MyException;
import com.example.result.MSG;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.*;

/**
 * 参数验证处理器
 * @Author: chen
 * @CreateTime: 2022-08-16
 * @Version: 1.0
 */
public class ParamsVerifyHandler {

    public static List<Class> verifyClass = new ArrayList<>();

    static {
        verifyClass.add(Length.class);
        verifyClass.add(NotNull.class);
        verifyClass.add(Phone.class);
    }

    //
    public static void verify(Object obj) {
        // 获取到对象
        Class clz = obj.getClass();
        // 属性列表
        List<Field> allFields = new ArrayList<>();
        // 获取当前类属性
        allFields.addAll(Arrays.asList(clz.getDeclaredFields()));
        // 如果有父类获取父类属性
        if (clz.getSuperclass() != null) {
            allFields.addAll(Arrays.asList(clz.getSuperclass().getDeclaredFields()));
        }
        Map<String,String> verifyMessage = new HashMap<>();
        for (Field field : allFields) {
            List<Annotation> fieldAnnotations = Arrays.asList(field.getAnnotations());
            for (Annotation fieldAnnotation : fieldAnnotations) {
                if (verifyClass.contains(fieldAnnotation.annotationType())) {
                    // 对应的注解事件
                    try {
                        field.setAccessible(true);
                        String message = VerifyHandler.verify(fieldAnnotation,field.get(obj));
                        if (message != null) {
                            verifyMessage.put(field.getName(),message);
                        }
                    }catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        if (verifyMessage.size() > 0) {
            MyException.display(MSG.PARAMS_ERROR,verifyMessage);
        }
    }
}
